//
//  ZAnimateBarItem.m
//  ZPlayer
//
//  Created by Zed Link on 26/11/2016.
//  Copyright © 2016 ZED. All rights reserved.
//

#import "ZAnimateBarItem.h"

@implementation ZAnimateBarItem

+ (instancetype)itemWithImageNames:(NSArray <NSString *> *)names duration:(NSTimeInterval)duration target:(id)target selector:(SEL)selector
{
    NSAssert(names.count >= 2, @"BarButtonItem上动画图片的数量至少需要2张");
    
    // ========== ImageView, 设置动画 ==========
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:names[0]]];
    
    NSMutableArray *tempArrM = [NSMutableArray arrayWithCapacity:names.count];
    // 按照 0, 1, 2, 3, 2, 1的顺序播放动画
    for (int i = 0; i < names.count * 2 - 2; i++) {
        unsigned long index = i < names.count ? i : (names.count - 1) - (i - names.count);
        UIImage *image = [UIImage imageNamed:names[index]];
        [tempArrM addObject:image];
    }
    imgView.animationImages = tempArrM;
    imgView.animationDuration = duration;
    
    ZAnimateBarItem *item = [[self alloc] initWithCustomView:imgView];
    item.imgView = imgView;
    
    // ========== 添加手势 ==========
    // 使用BarButtonItem的target与action不响应, 由imgView的手势来响应事件
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:selector];
    [imgView addGestureRecognizer:tap];
    
    return item;
}

- (void)beginAnimation
{
    if (self.imgView.isAnimating == NO) {
        [self.imgView startAnimating];
    }
}

- (void)endAnimation
{
    if (self.imgView.isAnimating == YES) {
        [self.imgView stopAnimating];
    }
}

@end
